/**
 * 漫游路线
 * @copyright 火星科技 mars3d.cn
 * @author 火星胡椒 2022-01-10
 */
import { logWarn } from "@mars/utils/mars-util"
import * as mars3d from "mars3d"

let map: mars3d.Map // 地图对象
let graphicLayer: mars3d.layer.GraphicLayer
let roamLine: mars3d.graphic.FixedRoute
let initialMultiplier = null // 最初的漫游速度

// 事件对象，用于抛出事件给vue
export const eventTarget = new mars3d.BaseClass()

// 初始化当前业务
export function onMounted(mapInstance: mars3d.Map): void {
  map = mapInstance // 记录map

  graphicLayer = new mars3d.layer.GraphicLayer()
  map.addLayer(graphicLayer)
}

// 释放当前业务
export function onUnmounted(): void {
  map.trackedEntity = undefined

  if (graphicLayer) {
    graphicLayer.destroy() // 销毁内部会释放所有事件及数据
    graphicLayer = null
  }
  if (initialMultiplier) {
    map.clock.multiplier = initialMultiplier
  }

  eventTarget.off()
  map = null
}

// let cameraType: string
/**
 * 根据传来的数据，重新绘制一条漫游路线
 *
 * @export
 * @param {any} data 对象
 * @returns
 */
export function getRoamLineData(data: any) {
  if (!data) {
    logWarn("没有获取到传递过来的数据")
    return
  }
  graphicLayer.clear()

  roamLine = new mars3d.graphic.FixedRoute(data)
  graphicLayer.addGraphic(roamLine)

  roamLine.start()

  roamLine.on(mars3d.EventType.change, mars3d.Util.funThrottle((event) => {
    // 取实时信息，可以通过  fixedRoute.info
    eventTarget.fire("roamLineChange", event)
  }, 500))

  initialMultiplier = map.clock.multiplier
  return map.clock.multiplier * 120
}

/**
 * 视角参数发生改变
 *
 * @export
 * @param {*} params 对象 {}
 * @returns {void}
 */
export function setCameraOptions(params: any) {
  roamLine.setCameraOptions(params)
}

export function updateMultiplier(num:number) {
  map.clock.multiplier = num / 120
}

// 停止漫游
export function stopRoamLine() {
  roamLine.stop()
}

// 显示剖面图
export function getTerrainHeight(): Promise<any> {
  return roamLine.getTerrainHeight({ splitNum: 100 })
}

// ui层使用
export const formatDistance = mars3d.MeasureUtil.formatDistance
export const formatTime = mars3d.Util.formatTime
